<template>
  <div class="user-role-management">
    <h1>用户角色管理</h1>
    
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户角色分配</span>
          <el-button type="primary" @click="showBatchAssignDialog">
            <el-icon><Plus /></el-icon>
            批量分配角色
          </el-button>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchForm.username"
              placeholder="用户名"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="searchForm.realName"
              placeholder="真实姓名"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="searchForm.roleId"
              placeholder="选择角色"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="role in availableRoles"
                :key="role.id"
                :label="role.roleName"
                :value="role.id"
              />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 用户列表 -->
      <el-table 
        :data="users" 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realName" label="真实姓名" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="当前角色" min-width="200">
          <template #default="scope">
            <el-tag 
              v-for="role in scope.row.roles" 
              :key="role.id" 
              size="small" 
              style="margin-right: 5px; margin-bottom: 5px;">
              {{ role.roleName }}
              <el-icon 
                class="el-icon--right" 
                @click="removeUserRole(scope.row.id, role.id)"
                style="cursor: pointer;">
                <Close />
              </el-icon>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="showRoleAssignDialog(scope.row)">
              分配角色
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 角色分配对话框 -->
    <el-dialog 
      v-model="roleAssignDialogVisible" 
      title="分配角色"
      width="600px">
      <div v-if="currentUser">
        <p><strong>用户：</strong>{{ currentUser.username }} ({{ currentUser.realName }})</p>
        <p><strong>当前角色：</strong>
          <el-tag 
            v-for="role in currentUser.roles" 
            :key="role.id" 
            size="small" 
            style="margin-right: 5px;">
            {{ role.roleName }}
          </el-tag>
        </p>
        
        <el-divider />
        
        <div>
          <p><strong>选择角色：</strong></p>
          <el-checkbox-group v-model="selectedRoleIds">
            <el-checkbox 
              v-for="role in availableRoles" 
              :key="role.id" 
              :label="role.id">
              {{ role.roleName }} - {{ role.description }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleAssignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="assignRoles" :loading="roleAssignLoading">
            确定分配
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量分配角色对话框 -->
    <el-dialog 
      v-model="batchAssignDialogVisible" 
      title="批量分配角色"
      width="600px">
      <div>
        <p><strong>已选择用户：</strong>{{ selectedUsers.length }} 人</p>
        <p><strong>用户列表：</strong></p>
        <el-tag 
          v-for="user in selectedUsers" 
          :key="user.id" 
          size="small" 
          style="margin-right: 5px; margin-bottom: 5px;">
          {{ user.username }} ({{ user.realName }})
        </el-tag>
        
        <el-divider />
        
        <div>
          <p><strong>选择角色：</strong></p>
          <el-checkbox-group v-model="batchSelectedRoleIds">
            <el-checkbox 
              v-for="role in availableRoles" 
              :key="role.id" 
              :label="role.id">
              {{ role.roleName }} - {{ role.description }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchAssignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="batchAssignRoles" :loading="batchAssignLoading">
            确定分配
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Close } from '@element-plus/icons-vue'
import { userApi, roleApi } from '../api'

// 响应式数据
const users = ref([])
const loading = ref(false)
const availableRoles = ref([])
const selectedUsers = ref([])

// 搜索表单
const searchForm = ref({
  username: '',
  realName: '',
  roleId: null
})

// 分页
const pagination = ref({
  current: 1,
  size: 20,
  total: 0
})

// 角色分配相关
const roleAssignDialogVisible = ref(false)
const currentUser = ref(null)
const selectedRoleIds = ref([])
const roleAssignLoading = ref(false)

// 批量分配相关
const batchAssignDialogVisible = ref(false)
const batchSelectedRoleIds = ref([])
const batchAssignLoading = ref(false)

// 加载用户列表
const loadUsers = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.value.current,
      size: pagination.value.size,
      ...searchForm.value
    }
    
    const response = await userApi.getUserList(params)
    if (response.data.code === 200) {
      users.value = response.data.data?.records || []
      pagination.value.total = response.data.data?.total || 0
    } else {
      throw new Error(response.data.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error(error.message || '加载失败')
    // 使用模拟数据作为后备
    users.value = [
      {
        id: 1,
        username: 'admin',
        realName: '管理员',
        email: 'admin@example.com',
        status: 1,
        roles: [
          { id: 1, roleName: '超级管理员' },
          { id: 2, roleName: '系统管理员' }
        ]
      }
    ]
    pagination.value.total = users.value.length
  } finally {
    loading.value = false
  }
}

// 加载可用角色列表
const loadAvailableRoles = async () => {
  try {
    const response = await roleApi.getRoleList()
    if (response.data.code === 200) {
      availableRoles.value = response.data.data || []
    } else {
      throw new Error(response.data.message || '获取角色列表失败')
    }
  } catch (error) {
    console.error('加载角色列表失败:', error)
    ElMessage.error('加载角色列表失败')
    // 使用模拟数据作为后备
    availableRoles.value = [
      { id: 1, roleName: '超级管理员', description: '系统最高权限' },
      { id: 2, roleName: '系统管理员', description: '系统管理权限' },
      { id: 3, roleName: '普通用户', description: '基本操作权限' }
    ]
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  loadUsers()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    username: '',
    realName: '',
    roleId: null
  }
  pagination.value.current = 1
  loadUsers()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.value.size = size
  pagination.value.current = 1
  loadUsers()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.value.current = current
  loadUsers()
}

// 选择改变
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

// 显示角色分配对话框
const showRoleAssignDialog = async (user) => {
  currentUser.value = user
  selectedRoleIds.value = user.roles?.map(role => role.id) || []
  roleAssignDialogVisible.value = true
  
  // 如果还没有加载角色列表，则加载
  if (availableRoles.value.length === 0) {
    await loadAvailableRoles()
  }
}

// 分配角色
const assignRoles = async () => {
  if (!currentUser.value) return
  
  try {
    roleAssignLoading.value = true
    
    const response = await userApi.assignRoles(currentUser.value.id, selectedRoleIds.value)
    if (response.data.code === 200) {
      ElMessage.success('角色分配成功')
      // 更新本地用户数据
      currentUser.value.roles = availableRoles.value.filter(role => 
        selectedRoleIds.value.includes(role.id)
      )
      // 刷新用户列表
      await loadUsers()
      roleAssignDialogVisible.value = false
    } else {
      throw new Error(response.data.message || '角色分配失败')
    }
  } catch (error) {
    console.error('角色分配失败:', error)
    ElMessage.error(error.message || '角色分配失败')
  } finally {
    roleAssignLoading.value = false
  }
}

// 移除用户角色
const removeUserRole = async (userId, roleId) => {
  try {
    await ElMessageBox.confirm('确定要移除这个角色吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await userApi.removeUserRole(userId, roleId)
    if (response.data.code === 200) {
      ElMessage.success('角色移除成功')
      // 刷新用户列表
      await loadUsers()
    } else {
      throw new Error(response.data.message || '角色移除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('角色移除失败:', error)
      ElMessage.error(error.message || '角色移除失败')
    }
  }
}

// 显示批量分配对话框
const showBatchAssignDialog = () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请先选择要分配角色的用户')
    return
  }
  
  batchSelectedRoleIds.value = []
  batchAssignDialogVisible.value = true
  
  // 如果还没有加载角色列表，则加载
  if (availableRoles.value.length === 0) {
    loadAvailableRoles()
  }
}

// 批量分配角色
const batchAssignRoles = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请先选择用户')
    return
  }
  
  if (batchSelectedRoleIds.value.length === 0) {
    ElMessage.warning('请先选择要分配的角色')
    return
  }
  
  try {
    batchAssignLoading.value = true
    
    const userIds = selectedUsers.value.map(user => user.id)
    const response = await userApi.batchAssignRoles(userIds, batchSelectedRoleIds.value)
    
    if (response.data.code === 200) {
      ElMessage.success('批量角色分配成功')
      // 刷新用户列表
      await loadUsers()
      batchAssignDialogVisible.value = false
      selectedUsers.value = []
    } else {
      throw new Error(response.data.message || '批量角色分配失败')
    }
  } catch (error) {
    console.error('批量角色分配失败:', error)
    ElMessage.error(error.message || '批量角色分配失败')
  } finally {
    batchAssignLoading.value = false
  }
}

onMounted(() => {
  loadUsers()
  loadAvailableRoles()
})
</script>

<style scoped>
.user-role-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}
</style>
